package main

import (
	"bufio"
	"context"
	"encoding/hex"
	"fmt"
	"net"
	"os"
	"os/signal"
	"time"
)

const (
	identifier = "862014056321489"
)

func main() {
	// 服务器地址和端口
	//serverAddress := "106.15.50.50:8080"
	serverAddress := "127.0.0.1:8080"

	// 连接到服务器
	conn, err := net.Dial("tcp", serverAddress)
	if err != nil {
		fmt.Println("连接失败:", err)
		return
	}
	//defer conn.Close() // 确保连接在结束时关闭

	fmt.Println("连接成功到", serverAddress)

	go push(conn)
	go receive(conn)

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	fmt.Println("Shutdown Server ...")

	_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	fmt.Println("Server exiting")
}

func push(conn net.Conn) {
	// 发送消息
	message := "534708000501000D07FFFF0300022B32322E35998850161F0900100868484072058305898608411924D32465601100120045"
	msgByte, err := hex.DecodeString(message)
	if err != nil {
		fmt.Errorf("dddd:, %v", err)
	}
	_, err = conn.Write(msgByte)
	if err != nil {
		fmt.Println("发送失败:", err)
		return
	}
	fmt.Println("消息发送:", message)

	for true {
		time.Sleep(30 * time.Second)
		heart := "53483145"
		data, _ := hex.DecodeString(heart)
		//if err != nil {
		//	fmt.Errorf("e:, %v", err)
		//}
		_, err = conn.Write(data)
		if err != nil {
			fmt.Println("发送失败:", err)
			return
		}
		fmt.Println("心跳发送:", string(data))
	}
}

func receive(conn net.Conn) {
	for true {
		time.Sleep(2 * time.Second)
		// 接收服务器回复
		reader := bufio.NewReader(conn)
		reply, err := reader.ReadString('E')
		if err != nil {
			fmt.Println("接收失败 没有收到数据:", err.Error())
			//return
		}
		fmt.Printf("receive %s\n", reply)
		cmd := reply[0:2]
		switch cmd {
		case "SA":
			data := reply[2 : len(reply)-1]
			dataStr := fmt.Sprintf("SA%s%sE", identifier, data)
			_, err := conn.Write([]byte(dataStr))
			if err != nil {
				fmt.Println("[SA]发送失败:", err)
				return
			}
			fmt.Printf("[SA] receive push %s \n", dataStr)
		case "SB":
			data := reply[2 : len(reply)-1]
			tt := fmt.Sprintf("SB%s%sE", identifier, data)
			_, err = conn.Write([]byte(tt))
			if err != nil {
				fmt.Println("[SB]发送失败:", err)
				return
			}
			fmt.Printf("[SB] receive push %x \n", tt)
		case "SC":
			data := reply[2 : len(reply)-1]
			dataStr := fmt.Sprintf("SC%s%sE", identifier, data)
			_, err = conn.Write([]byte(dataStr))
			if err != nil {
				fmt.Println("[SC]发送失败:", err)
				return
			}
			fmt.Printf("[SC] receive push %x \n", dataStr)
		case "SD":
			fmt.Printf("[SC] %s", reply)
		case "SF":
			data := reply[2 : len(reply)-1]
			dataStr := fmt.Sprintf("SF%s%sE", identifier, data)
			_, err = conn.Write([]byte(dataStr))
			if err != nil {
				fmt.Println("[SF]发送失败:", err)
				return
			}
			fmt.Printf("[SF] receive push %x \n", dataStr)
		case "SE":
			fmt.Printf("[SE] %s \n", reply)
		case "SI":
			fmt.Printf("[SI] %s \n", reply)
		default:
			fmt.Printf("[default] %s \n", reply)
		}
	}
}
